package com.example.chapter04;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

import com.example.chapter04.util.DataUtil;

public class ActRequestActivity extends AppCompatActivity implements View.OnClickListener {
    private final String mRequest = "你睡了吗？";
    private ActivityResultLauncher<Intent> register;
    private TextView tv_response;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_act_request);
        TextView tv_request = findViewById(R.id.tv_request);
        tv_request.setText("待发送的信息为：" + mRequest);

        findViewById(R.id.btn_request).setOnClickListener(this);

        tv_response = findViewById(R.id.tv_response);

        register = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                o -> {
                    if (o != null) {
                        Intent intent = o.getData();
                        if (intent != null && o.getResultCode() == Activity.RESULT_OK) {
                            Bundle bundle = intent.getExtras();
                            String responseTime = bundle.getString("response_time");
                            String responseContent = bundle.getString("response_content");
                            String desc = String.format("收到返回信息：\n应答时间为%s\n应答内容为%s",
                                    responseTime,responseContent);
                            //把返回消息的详情显示在文本视图上
                            tv_response.setText(desc);

                        }
                    }
                });

    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(this, ActResponseActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("request_time", DataUtil.getNowTime());
        bundle.putString("request_content", mRequest);
        intent.putExtras(bundle);
        register.launch(intent);

    }
}